//
//  COProfileViewController.swift
//  CocoProject
//
//  Created by Ruthless on 2023/8/29.
//

import UIKit
import TZImagePickerController
import BRPickerView

class COProfileViewController: COBaseViewController {
    private var image: UIImage?
    private var name: String?
    private var age: Int?
    private var level: String?
    private var select: [FoodType] = []
    
    var content: [COProfileModel] = []
    private var contents: [FoodType] = [.italy, .france, .usa, .russia, .britain, .thailand, .japan, .other]

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        name = COUserManager.userInfo?.nickName
        age = COUserManager.userInfo?.age
        level = COUserManager.userInfo?.level
        configCell()
        let food = COUserManager.userInfo?.food ?? ""
        select = food.components(separatedBy: ",").filter({ item in
            !item.isEmpty
        }).map({ item in
            return FoodType(rawValue: Int(item) ?? 0) ?? .italy
        }) 
        collectionView.reloadData()
    }
    
    override func configUI() {
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().offset(0)
            make.top.equalToSuperview().offset(statusBarHeight+navHeight)
            make.height.equalTo(285)
        }
        
        view.addSubview(label)
        view.addSubview(collectionView)
        view.addSubview(doneButton)
        label.snp.makeConstraints { make in
            make.top.equalTo(tableView.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(22)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(18)
            make.top.equalTo(label.snp.bottom).offset(21)
            make.height.equalTo(78)
        }
        
        doneButton.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(20)
            make.bottom.equalToSuperview().offset(-32-bottomSafeHeight)
            make.height.equalTo(50)
        }
    }

    private lazy var tableView: UITableView = {
        let tableV = UITableView()
        tableV.separatorStyle = .none
        tableV.isScrollEnabled = false
        tableV.register(cellWithClass: COProfileTableViewCell.self)
        tableV.delegate = self
        tableV.backgroundColor = .rgba(17, 7, 41, 1)
        tableV.dataSource = self
        return tableV
    }()

    private lazy var label: UILabel = {
        let label = UILabel()
        label.font = .regular(14)
        label.textColor = .white
        label.text = "Label"
        
        return label
    }()
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: (SCREENWIDTH-36-40)/4, height: 33)
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 10
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .rgba(17, 7, 41, 1)
        cv.delegate = self
        cv.dataSource = self
        cv.register(cellWithClass: COCreateCollectionViewCell.self)
        return cv
    }()
    
    private lazy var doneButton: UIButton = {
        let btn = UIButton()
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = [UIColor.rgba(218, 67, 255).cgColor, UIColor.rgba(82, 28, 255).cgColor]
        bgLayer1.locations = [0, 1]
        bgLayer1.frame = CGRect(x: 0, y: 0, width: SCREENWIDTH-36, height: 50)
        bgLayer1.startPoint = CGPoint(x: 1, y: 0.56)
        bgLayer1.endPoint = CGPoint(x: 0.56, y: 0.56)
        btn.layer.insertSublayer(bgLayer1, at: 0)
        
        btn.setTitle("Submit", for: .normal)
        btn.titleLabel?.font = .medium(14)
        btn.setTitleColor(.white, for: .normal)
        
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 25
        
        btn.addTarget(self, action: #selector(submit), for: .touchUpInside)
        return btn
    }()
}

extension COProfileViewController {
    private func configCell() {
        content = []
        let photo = COProfileModel()
        photo.image = image
        photo.imageUrl = COUserManager.userInfo?.sculpture
        photo.name = "Profile photo"
        photo.action = {[weak self] in
            let pick = TZImagePickerController(maxImagesCount: 1, delegate: self)!
            self?.present(pick, animated: true)
        }
        content.append(photo)
        
        let name = COProfileModel()
        name.name = "Nickname"
        name.content = self.name ?? ""
        name.action = {[weak self] in
            self?.changeName()
        }
        content.append(name)
        
        let id = COProfileModel()
        id.name = "ID"
        id.content = "\(COUserManager.userInfo?.id ?? 0)"
        id.rightHidden = true
        content.append(id)
        
        let age = COProfileModel()
        age.name = "Age"
        age.content = "\(self.age ?? 0) years old"
        age.action = {[weak self] in
            var time: [String] = []
            for i in 0...200 {
                time.append("\(i)")
            }
            BRStringPickerView.showPicker(withTitle: "Please select your age", dataSourceArr: time, select: self?.age ?? 0) { result in
                guard let value = result?.value else {
                    return
                }
                
                self?.age = Int(value)
                self?.configCell()
            }
        }
        content.append(age)
        
        let level = COProfileModel()
        level.name = "Professional level"
        level.content = self.level ?? ""
        level.action = {[weak self] in
            let content = ["Empty", "Beginner", "Intermediate", "Advanced"]
            var level = self?.level ?? "Empty"
            if level.isEmpty {
                level = "Empty"
            }
            let index = content.firstIndex(of: level) ?? 0
            BRStringPickerView.showPicker(withTitle: "Professional level", dataSourceArr: content, select: index) { result in
                guard let value = result?.value else {
                    return
                }
                
                if value == "Empty" {
                    self?.level = ""
                } else {
                    self?.level = value
                }
                
                self?.configCell()
            }
        }
        content.append(level)
        
        tableView.reloadData()
    }
}

extension COProfileViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        content.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        57
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: COProfileTableViewCell.self)
        cell.model = content[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        content[indexPath.row].action?()
    }
    
    @objc
    private func changeName() {
        let alert = UIAlertController(title: "", message: "Please enter your nickname", preferredStyle: .alert)
        alert.addTextField()
        let action = UIAlertAction(title: "Done", style: .default) {[weak alert, weak self] action in
            guard let alert = alert, let tf = alert.textFields?.first else {
                return
            }
            self?.name = tf.text
            alert.dismiss(animated: true) {
                self?.configCell()
            }
        }
        let cancel = UIAlertAction(title: "Cancel", style: .cancel)
        alert.addAction(action)
        alert.addAction(cancel)
        self.present(alert, animated: true)
    }
    
    @objc
    private func submit() {
        uploadImage()
    }
    
    private func uploadImage() {
        self.view.makeToastActivity(.center)
        if let image = image {
            CONetwork.sendRequest(provider: homeProvider, target: .uploadImage(image: image)) { text in
                let photo = text.replacingOccurrences(of: "\"", with: "")
                self.updateMessage(photo)
            } failedBlock: { _, text in
                self.view.hideToastActivity()
                self.view.makeToast(text, position: .center)
            }
        } else {
            updateMessage("")
        }
        
    }
    
    private func updateMessage(_ image: String) {
        CONetwork.sendRequest(provider: loginProvider, target: .complete(nickName: name, sculpture: image.isEmpty ? nil : image, age: age, level: level, food: select.map({ item in
            "\(item.rawValue)"
        }).joined(separator: ","))) { text in
            self.view.hideToastActivity()
            guard let userInfo = COUserManager.userInfo else {
                return
            }
            
            if !image.isEmpty {
                userInfo.sculpture = image
            }
            if let age = self.age {
                userInfo.age = age
            }
            if let name = self.name {
                userInfo.nickName = name
            }
            
            userInfo.level = self.level ?? ""
            userInfo.food = self.select.map({ item in
                "\(item.rawValue)"
            }).joined(separator: ",")
            COUserManager.userInfo = userInfo
            
            self.navigationController?.popViewController()
        } failedBlock: { _, text in
            self.view.hideToastActivity()
            self.view.makeToast(text, position: .center)
        }

    }
}

extension COProfileViewController: TZImagePickerControllerDelegate {
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable : Any]]!) {
        self.image = photos.first
        self.configCell()
    }
}

extension COProfileViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let type = contents[indexPath.row]

        if select.contains(type) {
            select.removeAll { item in
                item == type
            }
        } else {
            select.append(type)
        }
        
        collectionView.reloadData {
            
        }
    }
}

extension COProfileViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        contents.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withClass: COCreateCollectionViewCell.self, for: indexPath)
        let type = contents[indexPath.row]
        cell.button.setTitle(type.tag, for: .normal)
//        cell.addLayer(select == type)
        cell.addLayer(select.contains(type))
        return cell
    }
}
